<?php
Cinnamon::loadClass('ArrayCollection');
Cinnamon::loadClass('DatabaseFilter');

class DatabasePeriodFilter extends DatabaseFilter {
	/**
	 * Creates an instance of DatabaseFilter
	 */
	public function __construct($title) {
		parent::__construct($title, Cinnamon::registry('db')->requests, 'request_utc_datetime');
		
		// initialize common timestamps
		$now 	= gmdate('Y-m-d H:i:s', gmstrtotime('now'));
		$today 	= gmdate('Y-m-d H:i:s', gmstrtotime('today'));
		$yest 	= gmdate('Y-m-d H:i:s', gmstrtotime('yesterday'));

		// initialize data for this filter
		$db = Cinnamon::registry('db');
		$this->data = new ArrayCollection( array(
			array('label'=>'', 'value'=>null),
			array('label'=>'Today', 'value'=>'today 00:00:00;tomorrow 00:00:00'),
			array('label'=>'Yesterday', 'value'=>'yesterday 00:00:00;today 00:00:00'),
			array('label'=>'Two days ago', 'value'=>'-2 days 00:00:00;yesterday 00:00:00'),
			array('label'=>'', 'value'=>null),
			array('label'=>'Last two days', 'value'=>'yesterday 00:00:00;tomorrow 00:00:00'),
			array('label'=>'Last five days', 'value'=>'-4 days 00:00:00;tomorrow 00:00:00'),
			array('label'=>'Last seven days', 'value'=>'-1 week 00:00:00;tomorrow 00:00:00'),
			array('label'=>'', 'value'=>null),
			array('label'=>'This week', 'value'=>'this Monday 00:00:00;tomorrow 00:00:00'),
			array('label'=>'Last two weeks', 'value'=>'-1 week 00:00:00s;tomorrow 00:00:00'),
			array('label'=>'Last four weeks', 'value'=>'-3 weeks 00:00:00;tomorrow 00:00:00'),
			array('label'=>'', 'value'=>null),
			array('label'=>'This month', 'value'=>'this month;tomorrow 00:00:00'),
			array('label'=>'Last two months', 'value'=>'-1 months;tomorrow 00:00:00'),
			array('label'=>'Last four months', 'value'=>'-3 months;tomorrow 00:00:00'),
			array('label'=>'Last six months', 'value'=>'-5 months;tomorrow 00:00:00')
		) );
	}
	
	/**
	 * @see IFilter::filter()
	 */
	public function filter($collection) {
		if ( $collection instanceof DatabaseCollection ) {
			if ( strcasecmp($collection->getTable(), $this->table) == 0 && $this->selected->value != null ) {
				$p = explode(';', $this->selected->value);
				foreach ( $p as $i=>$v ) {
					if ( $v == 'this month' )
						$v = gmmktime(0, 0, 0, gmdate('m'), 1, gmdate('Y'));
					else if ( preg_match('/^([+-]?[0-9]+)\s*months$/i', $v, $matches) )
						$v = gmmktime(0, 0, 0, gmdate('m') + intval($matches[1]), 1, gmdate('Y'));
					else
						$v = gmstrtotime($v);
					$p[$i] = $v;
				}
				
				$collection->filter($this->table .'.'. $this->field .' >= ?', gmdate('Y-m-d H:i:s', $p[0]));
				$collection->filter($this->table .'.'. $this->field .' <= ?', gmdate('Y-m-d H:i:s', $p[1]));
			}
		}
	}
}
?>